package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.PostBean;
import com.project.bean.UserBean;
import com.project.service.IPostService;
import com.project.util.ValidAdd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDate;

@RestController
@RequestMapping("post")
public class PostController {
    @Autowired
    private IPostService service;

    @RequestMapping("findByItem")
    public IPage<PostBean> findByItem(Integer pageNO, Integer channelId,
                                      String title, String username,
                                      LocalDate startDate, LocalDate endDate,
                                      HttpServletRequest req) {

        return service.cutByItem(pageNO, channelId, title, username, startDate, endDate);
    }

    @RequestMapping("add")
    public String add( PostBean post, HttpServletRequest req,
                      BindingResult result) throws Exception{

//        if (result.hasErrors()){
//            ObjectMapper om = new ObjectMapper();
//            String str = om.writeValueAsString(result.getFieldErrors());
//            System.out.println(str);
//            return str;
//        }
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        post.setUserId(user.getId());

        service.add(post);
        return "ok";
    }

    @RequestMapping("findById")
    public PostBean findById(Integer id){
       return service.findById(id);
    }
}
